const mongoose = require('mongoose');

// 连接数据库
mongoose.connect(
  'mongodb://localhost:27017/vue_project', {
    useNewUrlParser: true,
    useFindAndModify: false
  }
)

// 连接验证
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
  console.log('数据库连接成功');
});

// 创建schema
const GoodsListSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true //设置必填项
  },
  now: {
    type: Number,
    required: true
  },
  old: {
    type: Number,
    required: true
  },
  remain: {
    type: Number,
    required: true
  }
});

// 实例化集合
const GoodsList = mongoose.model('Goodslist', GoodsListSchema);

const getGoodsList = function (callback) {
  GoodsList.find({}, (err, result) => {
    if (err) throw new Error('查询数据失败');
    callback(result);
  })
}

const getGoodsInfo = function (id, callback) {
  GoodsList.findById(id, (err, result) => {
    if (err) {
      try {
        throw new Error('无此id');
      } catch (error) {
        console.log('查无此id');
      }
    }
    callback(result);
  });
}

// 导出数据
exports.getGoodsList = getGoodsList;
exports.getGoodsInfo = getGoodsInfo;

// 单元测试
// //* 获取数据库数据模块，测试成功
// getGoodsList((result) => {
//   console.log(result);
// })